package com.solarfridge.monitor.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootPanel;
import com.solarfridge.monitor.shared.data.Fridge;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Solar_Fridge_Monitor implements EntryPoint, FridgeListBinder.FridgeDetailDisplayer, FridgeDetailsBinder.FridgeListReturner {
	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";

	/**
	 * Create a remote service proxy to talk to the server-side Data service.
	 */
	private final DataServiceAsync dataQueryService = 
		DataService.Util.getInstance();
	
	/**
	 * This is the entry point method. Loads the fridge list heading
	 * and queries the server for a list of fridges.
	 */
	public final void onModuleLoad() {
		returnToFridgeList();		
	}
	
	/**
	 * Clears the previous UI elements and displays a table
	 * of the fridge details.
	 * @param targetFridge The specified fridge to display
	 */
	public void displayFridgeDetails(final Fridge targetFridge) {
		final FridgeDetailsBinder detailsBinder = new FridgeDetailsBinder(targetFridge, this);
		RootPanel.get().clear();
		RootPanel.get().add(detailsBinder);
	}
	
	public void returnToFridgeList(){
		final FridgeListBinder fridgeListBinder = new FridgeListBinder(this);
		RootPanel.get().clear();
		RootPanel.get().add(fridgeListBinder);
		
		dataQueryService.getFridgeList(new AsyncCallback<Fridge[]>() {
			@Override
			public void onFailure(final Throwable caught) {
				fridgeListBinder.showErrorMessage(SERVER_ERROR);				
			}

			@Override
			public void onSuccess(final Fridge[] result) {
				if (result == null) {
					fridgeListBinder.showErrorMessage(SERVER_ERROR);				
				}				
				fridgeListBinder.populateFridgeTable(result);
			}
		});
	}
	
}
